﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Search.Web.Models;
using Webdiyer.WebControls.Mvc;

namespace Search.Web.Controllers
{
    public class LastSearchController : Controller
    {
        string indexPath = System.Configuration.ConfigurationManager.AppSettings["lucenedir"];
        private SearchDemoContext db = new SearchDemoContext();
        int page = 1;
        int size = 4;
        public ActionResult Index(string txtSearch, bool? hidfIsOr, int id = 1)
        {
            PanGuLuceneHelper.Instance.DeleteAll();
            // if (txtSearch == null) throw new ArgumentNullException(nameof(txtSearch));
            PagedList<MySearchUnit> list2 = null;
            
            if (!string.IsNullOrEmpty(txtSearch)) //如果点击的是查询按钮
            {
                //list = Search(txtSearch);
                // list = (hidfIsOr == null || hidfIsOr.Value == false) ? AndSearch(txtSearch, id) : OrSearch(txtSearch, id);

                #region 创建索引

                var articles = db.Article.ToList();
                var referList =
                    articles.Select(s => new MySearchUnit(s.ArticleId.ToString(), s.Title, s.Content, "1", "", ""))
                        .ToList();
                PanGuLuceneHelper.Instance.CreateIndex(referList);

                #endregion

                var totalCount = 0;
                var result = PanGuLuceneHelper.Instance.Search("1", txtSearch, page, size, out totalCount);

                #region  //先将搜索的词插入到明细表。  这里可以异步

                var searchDetail = new SearchDetail
                {
                    Id = Guid.NewGuid(),
                    KeyWords = txtSearch,
                    SearchDateTime = DateTime.Now
                };
                db.SearchDetail.Add(searchDetail);
                int r = db.SaveChanges();

                #endregion
                var keyWords =
                   db.SearchTotal.OrderByDescending(a => a.SearchCounts)
                       .Select(x => x.KeyWords)
                       .Skip(0)
                       .Take(6)
                       .ToList();
                ViewBag.KeyWords = keyWords;
                if (result == null)
                {
                    return View(list2);
                }
                list2 = result.ToPagedList<MySearchUnit>(page, size);
            }
            return View(list2);
        }



    }
}